package com.dcivision.dms.core;

import java.io.InputStream;
import java.sql.Connection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationContainer;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.FullTextIndexFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.IndexManager;
import com.dcivision.framework.SessionContainer;
/**
 * @deprecated This class has deprecated.
 */
public class IndexInBatchBackgroundThread extends Thread {
  protected Log log = LogFactory.getLog(this.getClass().getName());
  private SessionContainer sessionContainer = null;
  private String mode = null;
  private List documentIds = null;
  private String[] fields = null;
  
  /**
   * Class constructor specifying the dmsDocument object, inputStream data, mode and lucene document field
   * to be insert, update or delete.
   *  
   * @param dmsDocument the dmsDocument object
   * @param documentIds the handled document id list
   * @param mode        Operation mode, GlobalConstant.OP_MODE_UPDATE, GlobalConstant.OP_MODE_UPDATE or 
   *                    GlobalConstant.OP_MODE_DELETE      
   * @see com.dcivision.framework.GlobalConstant
   * @see com.dcivision.dms.core.DmsIndexConverter
   */
  public IndexInBatchBackgroundThread(SessionContainer sessionContainer, List documentIds, String mode, String[] fields) {
    super();
    this.sessionContainer = sessionContainer;
    this.documentIds = documentIds;
    this.mode = mode;
    this.fields = fields;
    
  }
  
  
 
  public void run() {
    long startTime = System.currentTimeMillis();
    Connection conn = null;
    ApplicationContainer container = this.sessionContainer.getAppContainer();
    String cacheKey = "I"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
    try {
      container.lockDocumentOperationID(cacheKey, this.documentIds);
      conn = DataSourceFactory.getConnection();
      
      DocumentRetrievalManager retrievalManager = new DocumentRetrievalManager(this.sessionContainer, conn);
      DocumentOperationManager operationManager = new DocumentOperationManager(this.sessionContainer, conn);
      DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(this.sessionContainer, conn);

      IndexManager idxHandler = FullTextIndexFactory.getInstance();
      DmsDocument dmsDocument = null;
      
      for (int i=0; i<this.documentIds.size(); i++) {
        Integer id = (Integer)documentIds.get(i);
        dmsDocument = (DmsDocument) dmsDocumentDAO.getObjectByID(id);
        //step 1: 
        operationManager.indexToDB(dmsDocument, this.mode);
        
        //step 2:
        InputStream data = null;
        try {
          if (!DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())) {
            if (GlobalConstant.OP_MODE_INSERT.equals(mode)) {
              if (DmsDocument.FOLDER_TYPE.equals(dmsDocument.getDocumentType())) {
                data = null;
              }else {
                data = retrievalManager.getDataInputStreamByDocument(dmsDocument);
              }
              idxHandler.insertDocument(DmsIndexConverter.getIndexDocument(dmsDocument, data));
            } else if (DmsOperationConstant.MOVE_OPERATION.equals(mode)) {
              data = null;
              org.apache.lucene.document.Document doc = DmsIndexConverter.getIndexDocument(dmsDocument, data, fields);
              idxHandler.updateDocument(doc);
            } else if (GlobalConstant.OP_MODE_DELETE.equals(mode)) {
              dmsDocument.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
              org.apache.lucene.document.Document doc = DmsIndexConverter.getIndexDocument(dmsDocument, data, fields);
              idxHandler.updateDocument(doc);
            }
          }
          
          //step 3:
        } catch (Exception e) {
          log.error("Error when indexing document.", e);
        }finally{
          try { data.close(); } catch (Exception ignore) {} finally { data = null; }
        }
      }
      conn.commit();
    }catch (Exception ex) {
      log.error(ex, ex);
      try {conn.rollback();}catch (Exception e) {log.error(e, e);}
    }finally {
      try {conn.close();}catch(Exception ignore) {}finally {conn=null;}
      container.unlockDmsDocumentOperationID(cacheKey);
    }
    log.debug("Index Background Thread Run Total: "+(System.currentTimeMillis()-startTime));
  }

  public void finalize() {
    this.destroy();
  }
  

  public void destroy() {
    this.sessionContainer = null;
    this.documentIds = null;
    this.mode = null;
  }

}